package com.ewins.weatherdataclient.interfacedatamodule;

import com.ewins.weatherdataclient.InfoEntity;
import com.ewins.weatherdataclient.common.Constant;
import com.ewins.weatherdatautils.bean.*;
import com.ewins.weatherdatautils.utils.Configuration;
import com.ewins.weatherdatautils.utils.SqliteAccess;
import com.google.common.eventbus.EventBus;
import javafx.scene.control.TextField;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 下载线程
 * Created by hp on 2015/12/3.
 */
public class InterfaceDataManagerHttp extends Thread {
    //数据库连接
    SqliteAccess sqliteAccess;
    /**
     * 下载文件情况
     */
    List<DownLoadFileInfo> waitingFiles = new ArrayList<DownLoadFileInfo>();

    //重新下载列表
    static List<DownLoadFileInfo> redownloadList = new ArrayList<DownLoadFileInfo>();
    DownLoadFileInfo redownloadFile;
    /**
     * 下载历史
     */
    List<DownLoadFileInfo> downLoadHistory = new ArrayList<DownLoadFileInfo>();

    /**
     * 上次更新的目录
     */
    HashSet<String> lastDownloadCatalog = new HashSet<String>();

    /**
     * 下载文件改变事件
     */
    FileLoadChangedInfo onChangedInfo;

    public FileLoadChangedInfo getOnChangedInfo() {
        return onChangedInfo;
    }

    public void setOnChangedInfo(FileLoadChangedInfo onChangedInfo) {
        this.onChangedInfo = onChangedInfo;
    }

    public List<DownLoadFileInfo> getWaitingFiles() {
        return waitingFiles;
    }
    //    /**
//     * 下载线程池
//     */
//    ThreadPoolExecutor downloadPool;

    /**
     * 监控线程池
     */
    ThreadPoolExecutor monitorPool;

    /**
     * 上次更新目录时间
     */
    DateTime lastUpdateCatalogTime = null;

    boolean needStop = false;
    boolean isFirst =true;        //是否是第一次启动
    EventBus eb;
    //过滤文件类型列表
    static ArrayList<PathNode> pathNodeList=new ArrayList<PathNode>();
    //需要下载的子路径列表
    static ArrayList<String> childPathNode=new ArrayList<String>();
    boolean isOpenNewTab =false;        //是否新建标签页
    int tabNumber;                  //过滤规则数
    static String tabType;     //过滤规则类型
    static String localUrl="";       //本地文件保存路径
    static HashMap<String,String> policyMap=new HashMap<String, String>();
    String filePath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "config.properties";
    Logger log= Logger.getLogger(InterfaceDataManagerHttp.class);

    public InterfaceDataManagerHttp(EventBus eb, ThreadPoolExecutor monitorPool){

        this.monitorPool=monitorPool;
        this.eb=eb;
    }

    public void run() {
        init();
        while (!needStop) {
            //SysLogger.info("更新目录");
            //更新目录
            updateCatalog();
            //将重新下载文件列表添加到等待下载列表
            if(redownloadList.size()>0){
                waitingFiles.addAll(redownloadList);
                redownloadList.clear();
            }
            //获取待下载文件中优先级最高的文件,最先下载
            DownLoadFileInfo needLoadFile = getTopFileInfo();
            if (needLoadFile != null) {
                //boolean canload = checkCanLoading(needLoadFile.getFilePriority());

                //计算线程池存在空闲线程数目，并且有文件需要下载则开始下载
                int freeLoadCount = Constant.DownLoadThreadCount - monitorPool.getActiveCount();
                System.out.println("空闲下载线程数目为：" + freeLoadCount);
                if (freeLoadCount > 0) {
                    //将结果post给 FileDownloadMonitor
                    DownloadInfos downloadInfos = new DownloadInfos();
                    downloadInfos.setNeedLoadFile(needLoadFile);
                    downloadInfos.setOnChangedInfo(onChangedInfo);
                    eb.post(downloadInfos);
                }
            }
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {

            }
        }
    }

    /**
     * 停止下载服务
     */
    public void stopServer()
    {
        needStop = true;
        checkCanLoading(-1);//关闭所有的下载线程
        monitorPool.shutdownNow();//关闭线程池
    }

    private void init() {
//        SysLogger.load();
//        downloadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(Constant.ThreadPoolMaxThreadCount);

        //monitorPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(Constant.DownLoadThreadCount);

        lastUpdateCatalogTime = DateTime.now().plusSeconds(0 - Constant.Update_DownLoad_Catalog_Time);
    }

    private DownLoadFileInfo getWeatherFileInfo(String url,String fileName,int priority)
    {
        DownLoadFileInfo fileInfo = new DownLoadFileInfo();
        fileInfo.setLocalFilePath(Constant.Local_DownLoad_Path);
        fileInfo.setFileName(fileName);
        fileInfo.setUrl(url);
        fileInfo.setFilePriority(priority);
        fileInfo.setCreatedTime(DateTime.now());
        fileInfo.setState(DownLoadState.WaitingLoad);
        return  fileInfo;
    }

    int indexCatalog = 0;
    /**
     * 更新下载的目录
     */
    private void updateCatalog()
    {
        int seconds = Seconds.secondsBetween(lastUpdateCatalogTime,DateTime.now()).getSeconds();
        if(seconds > Constant.Update_DownLoad_Catalog_Time){
            //更新需要下载文件目录
            updateCatalog2();

            lastUpdateCatalogTime = DateTime.now();

            if(onChangedInfo != null)
            {
                //System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
                //Collections.sort(waitingFiles, comparator);         //文件排序：创建时间排序
                onChangedInfo.changed(waitingFiles,isOpenNewTab,tabType);
                //onChangedInfo.downloadHistory(downLoadHistory);   //已下载的文件列表
            }
            this.isOpenNewTab=false;
        }
    }

    /**
     * 更新需要下载的目录，并生成下载文件信息列表
     */

    private void updateCatalog2()
    {
        try {
            List<DownLoadCategory> downloadList = getDownloadList();
            if(downloadList != null){
                HashSet<String> downloadCatalog = new HashSet<String>();
                    //category.setCategoryName(downloadList.getCategoryName());
                    for (int i = 0;i< downloadList.size();i++){
                        JSONObject jsonObject= JSONObject.fromObject(downloadList.get(i));
                        JSONArray jsonArray=jsonObject.getJSONArray("category");
                        //文件类型名称
                        String categoryName=jsonObject.get("categoryName").toString();

                        for(int j=0;j<jsonArray.size();j++){
                            JSONObject jo=JSONObject.fromObject(jsonArray.get(j));
                            DownLoadFile loadfile=(DownLoadFile)jo.toBean(jo,DownLoadFile.class);

                            //第一次启动
                            if (isFirst) {
                                //查询本地数据库文件列表，如果本地未下载该文件，则添加到文件列表
                                if (!searchLocalFileList(loadfile.getName(), loadfile.getDatetime())) {
                                    waitingFiles.add(getDownLoadFileInfo(loadfile, categoryName));
                                }
                                downloadCatalog.add(loadfile.getName());


                            } else  {
                                //if(!searchLocalFileList(loadfile.getName(),loadfile.getDatetime())) {
                                    if (!lastDownloadCatalog.contains(loadfile.getName())) {
                                        waitingFiles.add(getDownLoadFileInfo(loadfile, categoryName));
                                    }
                                //}
                                downloadCatalog.add(loadfile.getName());
                            }

                        }

                    }
                    this.isFirst=false;
                    //过滤要求的文件类型
//                    ArrayList<DownLoadFileInfo> dlfis=new ArrayList<DownLoadFileInfo>();
//                    for(DownLoadFileInfo dlfi:waitingFiles){
//
//                        String type= dlfi.getCategoryName();
//                        String suffix=dlfi.getFileName().substring(dlfi.getFileName().lastIndexOf(".")+1);
//                        //忽略大小写
//                        if(policyMap.get(type).equals("") || org.apache.commons.lang3.StringUtils.containsIgnoreCase(policyMap.get(type),suffix)){
//                            dlfis.add(dlfi);
//                        }
//                    }
//                    if(!dlfis.isEmpty()){
//                        waitingFiles=dlfis;
//                    }

                lastDownloadCatalog=null;
                lastDownloadCatalog = downloadCatalog;

                //清除下载列表中,未出现在下载目录中的下载文件信息
                for (int i = 0; i < waitingFiles.size(); i++) {
                    DownLoadFileInfo fileInfo = waitingFiles.get(i);
                    if(!lastDownloadCatalog.contains(fileInfo.getFileName())) {
                        if (DownLoadState.Loading.equals(fileInfo.getState())) {
                            fileInfo.setState(DownLoadState.Pause);
                        }
                        waitingFiles.remove(i);
                        i--;
                    }
                }

            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }


    /**
     * 获取下载文件信息
     * @param loadfile
     * @return
     */
    public static DownLoadFileInfo getDownLoadFileInfo(DownLoadFile loadfile, String categoryName) {
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DownLoadFileInfo fileInfo = new DownLoadFileInfo();
        String path=loadfile.getPath();
        path=path.replaceAll("/", "\\\\");

        //本地保存路径
        if(localUrl.equals("")){
            fileInfo.setLocalFilePath(Constant.Local_DownLoad_Path.substring(0,Constant.Local_DownLoad_Path.length()-1)+path);
        }else {
            fileInfo.setLocalFilePath(localUrl+path);
        }
        //文件重命名
//        if(path.contains("RADR_LATLON_OUT")){
////            int num=loadfile.getName().indexOf("2");
////            String name=loadfile.getName().substring(0,num+1)+loadfile.getName().substring(num + 16);
////            fileInfo.setFileName(name);
//            //String tmp[]=loadfile.getName().split("_");
//            //fileInfo.setFileName(loadfile.getName().replace(tmp[4],""));
//        }else{
//            fileInfo.setFileName(loadfile.getName());
//        }
        fileInfo.setFileName(loadfile.getName());
        //服务器下载路径
        path=path.replaceAll("\\\\","/");
        fileInfo.setUrl(Constant.DownLoadFileUrl + path + loadfile.getName());

        fileInfo.setFilePriority(convert2Int(loadfile.getPrior()));
        fileInfo.setCreatedTime(DateTime.parse(loadfile.getDatetime(), format));
        fileInfo.setState(DownLoadState.WaitingLoad);
        fileInfo.setCategoryName(categoryName);
        return fileInfo;
    }

    private static int convert2Int(String value)
    {
        try {
            return  Integer.parseInt(value);
        }catch ( Exception e){
            return 0;
        }
    }

    /**
     * 检查给定的优先级是否可以下载
     * 如果优先级高则暂停当前正在下载的文件，返回true
     * 如果优先级相等返回true
     * 如果优先级低则返回false
     * @param needLoadPriority
     * @return
     */
    private boolean checkCanLoading(int needLoadPriority)
    {
        int loadingPriority = needLoadPriority;
        for (int i = 0; i < waitingFiles.size(); i++) {
            DownLoadFileInfo currentloadFile = waitingFiles.get(i);
            if (DownLoadState.Loading.equals(currentloadFile.getState())) {
                loadingPriority = currentloadFile.getFilePriority();

                if (currentloadFile.getFilePriority() > needLoadPriority) {
                    //暂停正在下载的文件
                    log.info("暂停下载文件：" + currentloadFile.getFileName());
                    if (DownLoadState.WaitingLoad.equals(currentloadFile.getState()) || DownLoadState.Loading.equals(currentloadFile.getState())) {
                        currentloadFile.setState(DownLoadState.Pause);
                    }
                }
            }
        }
//        log.info("正在下载文件的优先级：" + loadingPriority);
        return loadingPriority >= needLoadPriority;
    }

    /**
     * 获取待下载文件中优先级最高的文件
     * 将已经下载完的记录清除
     */
    private DownLoadFileInfo getTopFileInfo() {
        Collections.sort(waitingFiles, comparator);         //文件排序：按优先级，创建时间排序
        DownLoadFileInfo result = null;
        //int priority = 10;
        for (int i = 0; i < waitingFiles.size(); i++) {
            DownLoadFileInfo fileInfo = waitingFiles.get(i);
            if (DownLoadState.WaitingLoad.equals(fileInfo.getState()) || DownLoadState.Pause.equals(fileInfo.getState())) {
                    String type= fileInfo.getCategoryName();
                    String suffix=fileInfo.getFileName().substring(fileInfo.getFileName().lastIndexOf(".")+1);
                    ////过滤要求的文件类型,忽略大小写
                    if(policyMap.get(type).equals("") || org.apache.commons.lang3.StringUtils.containsIgnoreCase(policyMap.get(type),suffix)){
                        if (result == null) {
                            result = fileInfo;
                        } else if (fileInfo.getCreatedTime().isAfter(result.getCreatedTime())) {
                            result = fileInfo;
                        }
                    }else {
                        waitingFiles.remove(i);
                        i--;
                    }
            } else if (DownLoadState.Finished.equals(fileInfo.getState())||DownLoadState.Error.equals(fileInfo.getState())) {
                //downLoadHistory.add(waitingFiles.get(i));
                waitingFiles.remove(i);
                i--;
            }

        }
        return result;
    }


    List<String> infoListHistory=new ArrayList<String>();      //未分块处理的.info文件

    //获取文件下载列表
    private List<DownLoadCategory> getDownloadList() {
        //变量声明
        String downlistjson;            //info文件列表信息
        InfoEntity infoEntity;          //.info文件实体

        List<DownLoadCategory> list=new ArrayList<DownLoadCategory>();  //待下载的文件列表
        List<InfoEntity> infoEntityList=new ArrayList<InfoEntity>();
        List<String> infoList=new ArrayList<String>();      //未分块处理的.info文件


        try {
            downlistjson = getjsonFromUrl(Constant.DownLoadCatalogUrl);
            if(null!=downlistjson && !downlistjson.equals("") && downlistjson.endsWith("}")){
                JSONObject jsonObject= JSONObject.fromObject(downlistjson);
                //从downloadlist.info文件中获取.info文件列表
                JSONArray jsonArray=jsonObject.getJSONArray("categories");

                //根据过滤规则，判断是否需要新增标签页 isOpenNewTab=true||false
                if(isFirst){
                    if(pathNodeList.size()>0){
                        tabNumber=childPathNode.size();
                        this.isOpenNewTab=true;
                    }
                }
                else {
                    if(tabNumber!=childPathNode.size()&&childPathNode.size()>0){
                        tabNumber=childPathNode.size();
                        this.isOpenNewTab=true;
                    }
                }

            //根据过滤规则，筛选出需要下载的.info文件
            String header= Configuration.GetValueByKey(filePath, "Header");
            if(pathNodeList.size()>0) {
                //解析完成的.info文件
                    for (int j = 0; j < jsonArray.size(); j++) {
                        String infoUrl = jsonArray.get(j).toString();
                        String[] tmp=infoUrl.split("&");
                        if(tmp.length==2){
                            String s=tmp[1].substring(0,tmp[1].length()-5);
                            if(policyMap.containsKey(s)){
                                infoUrl=infoUrl.replace(header,"");
                                infoList.add(infoUrl);
                            }
                        }
                        if(tmp.length==4){
                            String s=tmp[1];
                            if(policyMap.containsKey(s)){
                                infoUrl=infoUrl.replace(header,"");
                                infoEntity = new InfoEntity();
                                infoEntity.setInfoType(tmp[1]);
                                infoEntity.setUrl(infoUrl);
                                infoEntity.setCreateTime(Long.parseLong(tmp[2]));
                                infoEntityList.add(infoEntity);
                            }
                        }
                    }

                //解析拆分过的.info文件
                if(null!=infoEntityList && infoEntityList.size()>0) {

                    //下载列表数组去重
                    infoEntityList = new ArrayList<InfoEntity>(new HashSet<InfoEntity>(infoEntityList));

                    // 根据生成时间对infoEntityList 进行排序
                    Collections.sort(infoEntityList, comparators);

                    if(infoListHistory.size()==0){
                        //-json格式错误时，处理方法-//
                        while (true){
                            String str = getjsonFromUrl(Constant.DownLoadFileUrl + infoEntityList.get(0).getUrl());
                            if (null != str && !str.equals("") && str.endsWith("}]}")) {
                                try{
                                    JSONObject jo = JSONObject.fromObject(str);
                                    JSONArray ja = jo.getJSONArray("downLoadCategoryList");
                                    if (ja.size() > 0) {
                                        list.addAll(ja);
                                        infoListHistory.add(infoEntityList.get(0).getUrl());
                                        break;
                                    }
                                }catch (Exception e){
                                    log.error("拆分json文件解析异常：\r\n"+infoEntityList.get(0).getUrl());
                                    continue;
                                }
                            }
                            Thread.sleep(5000);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < infoEntityList.size(); i++) {
                            boolean exist=false;
                            for (int j = 0; j < infoListHistory.size(); j++)
                            {
                                if (infoListHistory.get(j).equals(infoEntityList.get(i).getUrl())) {
                                    exist=true;
                                    break;
                                }
                            }
                            if(!exist){
                                String str = getjsonFromUrl(Constant.DownLoadFileUrl + infoEntityList.get(i).getUrl());
                                if (null != str && !str.equals("") && str.endsWith("}]}")) {
                                    try {
                                        JSONObject jo = JSONObject.fromObject(str);
                                        JSONArray ja = jo.getJSONArray("downLoadCategoryList");
                                        if (ja.size() > 0) {
                                            list.addAll(ja);
                                            infoListHistory.add(infoEntityList.get(i).getUrl());
                                        }
                                    }catch (Exception e){
                                        log.error("拆分json文件解析异常：\r\n" + infoEntityList.get(i).getUrl());
                                        continue;   //当json文件格式错误时，跳出循环
                                    }

                                }
                            }
                        }
                    }

                }
                //解析未拆分处理的.info文件
                if(null!=infoList && infoList.size()>0) {

                    //下载列表数组去重
                    infoList  = new ArrayList<String>(new HashSet<String>(infoList));
                    String str="";
                    for (int i = 0; i < infoList.size(); i++) {
                        try {
                             str = getjsonFromUrl(Constant.DownLoadFileUrl + infoList.get(i));
                            if(null!=str && !str.equals("") && str.endsWith("}]}")){
                                JSONObject jo = JSONObject.fromObject(str);
                                JSONArray ja = jo.getJSONArray("downLoadCategoryList");
                                if (ja.size() > 0) {
                                    list.addAll(ja);
                                }
                            }
                        }catch (Exception e){
                            log.error("未拆分json文件解析异常:" + infoList.get(i));
                            continue;   //当json文件格式错误时，跳出循环
                        }


                    }
                }

            }

                if (!downlistjson.equals("")) {
    //                JSONArray jsonarray = JSONArray.fromObject(downlistjson);
                    //List<DownloadList> list = new Gson().fromJson(downlistjson,new TypeToken<List<DownloadList>>(){}.getType());
    //                        (List) JSONArray.toCollection(jsonarray, DownloadList.class);
                    if (list.size() > 0) {
    //                    JSONObject obj = new JSONObject().fromObject(downlistjson);//将json字符串转换为json对象
    //                    new JSONArray().fromObject(downlistjson)
    //                    DownloadList downlist = (DownloadList) JSONObject.toBean(obj, DownloadList.class);//将建json对象转换为Person对象
                        List<DownLoadCategory> downlist = list;

                        return downlist;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    private String getjsonFromUrl(String url)
    {
        HttpURLConnection connection = null;
        Reader reader= null;
        try {
            URL urlobject = new URL(url);

            connection = (HttpURLConnection) urlobject.openConnection();
            //connection.setSSLSocketFactory(HttpsDefault.getSSLSocketFactory());

            connection.setRequestProperty("User-Agent", "NetFox");
            int responseCode = connection.getResponseCode();

            if(responseCode!=200){
                return "";
            }

            connection.connect();
            InputStream inputStream = connection.getInputStream();
            //对应的字符编码转换
            reader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            StringBuffer sb = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        finally {
            try {
                if (connection != null)
                    connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 查询数据库，判断文件是否已下载
     * @throws Exception
     */
    public synchronized boolean searchLocalFileList(String name,String createTime){
        try {
             String path = System.getProperty("user.dir");
            String dbFileName = Configuration.GetValueByKey(path + File.separator + "config" + File.separator + "config.properties", "DBFILENAME");
            Class.forName("org.sqlite.JDBC");
            Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbFileName);
            conn.setAutoCommit(true);
            Statement stmt = conn.createStatement();

            String sql="select * from currentfile where filename ='"+name+"'";//+" and createTime ='"+createTime+"'";
            ResultSet rs = stmt.executeQuery(sql);

            if (rs.next() == false) {
                stmt.close();
                rs.close();
                conn.close();
                return false;       //该文件未下载
            } else {
                stmt.close();
                rs.close();
                conn.close();
                return true;        //该文件已下载
            }
        }catch (Exception E){
            log.error(E.getMessage());
        }
        return true;
    }

    //文件下载列表排序
    Comparator<DownLoadFileInfo> comparator = new Comparator<DownLoadFileInfo>(){
        public int compare(DownLoadFileInfo df1, DownLoadFileInfo df2) {
                //优先级相同则按创建时间倒序
                if(df1.getCreatedTime().isAfter(df2.getCreatedTime())){
                    return -1;
                }else if(df1.getCreatedTime().isEqual(df2.getCreatedTime())){
                    return 0;
                }
                else{
                    return 1;
                }
        }
    };
    //根据生成时间，对筛选后的.info文件列表排序
    Comparator<InfoEntity> comparators = new Comparator<InfoEntity>(){
        public int compare(InfoEntity ie1, InfoEntity ie2) {
            //按创建时间倒序
                if(ie1.getCreateTime()<(ie2.getCreateTime())){
                    return 1;
                }else if(ie1.getCreateTime()==(ie2.getCreateTime())){
                    return 0;
                }
                else{
                    return -1;
                }
            }
    };

    //获取重新下载文件信息
    public static void addRedownloadFile(DownLoadFile redownloadFile,String categoryName) {
        if (null != redownloadFile) {
            redownloadList.add(getDownLoadFileInfo(redownloadFile, categoryName));
        }
    }

    //获取过滤规则
    public static void  getPathNode(ArrayList<PathNode> pathNode,String downloadto){
        String tabcreateTime="";    //筛选的文件类型
        ArrayList<String> arrayList=new ArrayList<String>();
        if(pathNode.size()>0){
            pathNodeList.addAll(pathNode);
            policyMap.clear();
            for(PathNode pn:pathNodeList){
                policyMap.put(pn.getPath().substring(pn.getPath().lastIndexOf("/")+1),pn.getRule());
            }
        }
        if(pathNode.size()>0){
            for(int i=0;i<pathNode.size();i++){
                //将叶子节点路径添加到列表
                childPathNode.add(pathNode.get(i).getPath());
                String pathNodeStr=pathNode.get(i).getPath().substring(pathNode.get(i).getPath().lastIndexOf("/")+1);
                arrayList.add(pathNodeStr);
            }
            //每个标签页所包括的过滤规则
            arrayList=new ArrayList<String>(new HashSet<String>(arrayList));
            for(int i=0;i<arrayList.size();i++){
                tabcreateTime+=arrayList.get(i)+",";
            }
            tabType=tabcreateTime.substring(0,tabcreateTime.length()-1);
        }

        if(null!=downloadto){
            localUrl=downloadto;
        }

    }
}
